package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.enums.LoginEnum;
import com.qk.enums.ParamEnum;
import com.qk.exception.CommonException;
import com.qk.exception.LoginException;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import com.qk.utils.JwtUtils;
import com.qk.vo.user.UserLoginVO;
import com.qk.vo.user.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 *
 * @author lyl
 * @created 2025/9/30 15:24
 * @description
 *
 */
@Service
@SuppressWarnings("all")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    private static final String DEFAULT_PASSWORD_SUFFIX = "123";

    private static final Integer USER_STATUS_UNNORMAL = 0;


    @Override
    public PageResult<UserVO> list(UserDTO userDTO) {
        PageHelper.startPage(userDTO.getPage(), userDTO.getPageSize());
        List<UserVO> users = userMapper.list(userDTO);
        Page<UserVO> pages = (Page<UserVO>)users;
        return PageResult.<UserVO>builder()
                .total(new Long(pages.getTotal()).intValue())
                .rows(pages.getResult())
                .build();
    }

    @Override
    public void addUser(User user) {
        boolean hasNull = BeanUtil.hasNullField(user, "id","password", "dept_id", "role_id", "image", "remark", "create_time", "update_time");
        if (hasNull) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        String rawPassword = user.getUsername().concat(DEFAULT_PASSWORD_SUFFIX);
        String encodedPassword = DigestUtils.md5DigestAsHex(rawPassword.getBytes());
        user.setPassword(encodedPassword);
        userMapper.addUser(user);
    }

    @Override
    public List<User> listByDept(Integer deptId) {
        return userMapper.listByDept(deptId);
    }

    @Override
    public List<User> listByRole(String roleLabel) {
        return userMapper.listByRole(roleLabel);
    }

    @Override
    public List<User> getAll() {
        return userMapper.getAll();
    }

    @Override
    public void updateUser(User user) {
        boolean hasNull = BeanUtil.hasNullField(user, "dept_id", "role_id", "image", "remark", "update_time");
        if (hasNull){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateUser(user);
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.getUserById(id);
    }

    @Override
    public void deleteUsers(List<Integer> ids) {
        userMapper.deleteUsers(ids);
    }

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        if (BeanUtil.hasNullField(userLoginDTO)){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        User user = userMapper.getUserByUsername(userLoginDTO.getUsername());
        if (Objects.isNull(user)){
            LoginException.throwLoginException(LoginEnum.USER_NOT_EXIST);
        }
        String userPassword = DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes());
        if (!Objects.equals(user.getPassword(), userPassword)){
            LoginException.throwLoginException(LoginEnum.USER_PASSWORD_ERROR);
        }
        if (Objects.equals(user.getStatus(), USER_STATUS_UNNORMAL)){
            LoginException.throwLoginException(LoginEnum.USER_STATUS_ERROR);
        }
        Role role = roleMapper.getRoleById(user.getRoleId());
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("username", user.getUsername());
        claims.put("role", role.getLabel());
        String token = JwtUtils.generateToken(claims);
        return UserLoginVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .name(user.getName())
                .image(user.getImage())
                .roleLabel(role.getLabel())
                .token(token)
                .build();
    }

    @Override
    public List<String> getImages() {
        //获取当前时间的前一天
        //LocalDateTime yesterday = LocalDateTime.now().minusDays(1);
        return userMapper.getImages();
    }
}
